package com.syzygy.controller;

import com.alibaba.fastjson2.JSONArray;
import com.syzygy.pojo.Picture;
import com.syzygy.pojo.Type;
import com.syzygy.service.PictureService;
import com.syzygy.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import util.PictureUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/Picture")
public class PictureController {
    @Autowired
    PictureUtils pictureUtils;
    @Autowired
    private PictureService pictureService;
    @Autowired
    private TypeService typeService;

    //    查询所有Picture
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public List<Picture> getAllPicture() {
        return pictureService.getAllPicture();
    }

    //    图片上传
    @RequestMapping(value = "/", method = RequestMethod.POST)
    public String uploadPicture(@RequestParam("file") MultipartFile file,
                                HttpServletRequest request,
                                @RequestParam("typeId") int typeId,
                                @RequestParam("price") double price,
                                @RequestParam("describe") String describe,
                                HttpSession session) throws IOException {
        if (null != file) {
//        图片id
            String pictureId = pictureUtils.getPictureId();
//        图片路径前缀
            String pictureUrlPrefix = "D:/Syzygy/pictures/";
//        获取图片类型
            // 2 获取原始的文件名
            String pictureDocumentName = file.getOriginalFilename();
            // 3 先截取原文件的文件名后缀
            String pictureSuffix = pictureDocumentName.substring(pictureDocumentName.lastIndexOf("."), pictureDocumentName.length());
//        获取新图片名与图片路径
            String pictureUrl = pictureUrlPrefix + pictureId + pictureSuffix;
//        图片储存
            File newFile = new File(pictureUrl);
            newFile.getParentFile().mkdir();
            file.transferTo(newFile);
//
            System.out.println("上传成功");

//        用户Id
            int userId = -1;
            Object userIdSession = session.getAttribute("userId");
            if (userIdSession != null) {
                userId = Integer.parseInt(userIdSession.toString());
            } else {
                return "redirect:/";
            }

            String pictureNewDocumentName = pictureId + pictureSuffix;
            pictureService.uploadPicture(pictureId, pictureNewDocumentName, userId, typeId, price, describe);
        }
        return "redirect:/";

    }

    //    根据typeId查pictures
    @RequestMapping(value = "/TypeId/{typeId}", method = RequestMethod.GET)
    @ResponseBody
    public void getPicturesByTypeIdAJAX(@PathVariable int typeId,
                                        HttpServletResponse response
    ) throws IOException {
        List<Picture> picturesByTypeId = pictureService.getPicturesByTypeId(typeId);
        String picturesByTypeIdJSON = JSONArray.toJSONString(picturesByTypeId);
        System.out.println(picturesByTypeIdJSON);
        response.getWriter().print(picturesByTypeIdJSON);
    }

    //    图文卡片页面
    @RequestMapping("/Details/{pictureId}")
    protected String graphicCard(Model model, @PathVariable String pictureId) {
        Picture picture = pictureService.getPictureById(pictureId);
        model.addAttribute("picture", picture);
        return "pictureGraphicCard";
    }

    //    图片上传页面
    @RequestMapping("/Release")
    protected String releaseCard(Model model, HttpSession session) {
        List<Type> allType = typeService.getAllType();
        String allTypeJSON = JSONArray.toJSONString(allType);
        model.addAttribute("allTypeJSON", allTypeJSON);
        Object userIdString = session.getAttribute("userId");
        if (userIdString != null) {
            return "pictureReleaseCard";
        } else {
            return "redirect:/";
        }
    }

    //根据pictureId查Picture
    @RequestMapping(value = "/id/{pictureId}", method = RequestMethod.GET)
    public Picture getPictureById(@PathVariable String pictureId) {
        return pictureService.getPictureById(pictureId);
    }

    //根据id 信息更新
    @RequestMapping(value = "/id/", method = RequestMethod.PUT)
    public String updatePictureByPictureId(@RequestParam("describe") String describe,
                                           @RequestParam("typeId") int typeId,
                                           @RequestParam("price") double price,
                                           @RequestParam("pictureId") String pictureId,
                                           HttpSession session) {
        Object userIdSession = session.getAttribute("userId");
        Picture pictureById = pictureService.getPictureById(pictureId);
//      不为空
        if (userIdSession != null && userIdSession != "" && pictureById != null) {
            int userId = Integer.parseInt(userIdSession.toString());
//          符合
            if (userId == pictureById.getUserId()) {
                pictureService.updatePictureByPictureId(describe, typeId, price, pictureId);
                return "redirect:/User/Manage";
//          不符合
            } else {
                return "redirect:/";
            }
//      为空
        } else {
            return "redirect:/";
        }
    }

    //根据id 删除
    @RequestMapping(value = "/id/", method = RequestMethod.DELETE)
    public String deletePictureByPictureId(@RequestParam("pictureId") String pictureId, HttpSession session) {
        Object userIdSession = session.getAttribute("userId");
        Picture pictureById = pictureService.getPictureById(pictureId);
//      不为空
        if (userIdSession != null && userIdSession != "" && pictureById != null) {
            int userId = Integer.parseInt(userIdSession.toString());
//          符合
            if (userId == pictureById.getUserId()) {
                pictureService.deletePictureByPictureId(pictureId);
                return "redirect:/User/Manage";
//          不符合
            } else {
                return "redirect:/";
            }
//      为空
        } else {
            return "redirect:/";
        }
    }

    //根据id 更新状态
    @RequestMapping(value = "/state/", method = RequestMethod.PUT)
    public String updateStateByPictureId(@RequestParam("pictureId") String pictureId,
                                           @RequestParam("state") String state,HttpSession session){
        Object userIdSession = session.getAttribute("userId");
        Picture pictureById = pictureService.getPictureById(pictureId);
//      不为空
        if (userIdSession != null && userIdSession != "" && pictureById != null) {
            int userId = Integer.parseInt(userIdSession.toString());
//          符合
            if (userId == pictureById.getUserId()) {
                pictureService.updateStateByPictureId(state, pictureId);
                return "redirect:/User/Manage";
//          不符合
            } else {
                return "redirect:/";
            }
//      为空
        } else {
            return "redirect:/";
        }

    }


}
